Yes.
The reverse()
method
reverses the order of the characters in a StringBuffer
object.
Unlike the methods of immutable objects,
this method changes the data of its object.
For the following example, pretend that this method does not exist.
Our reverse()
inputs a reference to a String
and returns a reference to a reversed version of that String
.
Only two new objects
are created: the StringBuffer
and the
String
object that is returned to the caller.
The append()
method puts a new character at the end
of a StringBuffer
object.
No new object is created.
We can use this method to build up the reversed characters as
the original String
is scanned from right to left:
public class ReverseTester { public static String reverse( String data ) { StringBuffer temp = new StringBuffer(); for ( int j=data.length()-1; j >= 0; j-- ) // scan the String from right to left temp.append( data.charAt(j) ); // append characters on the right return temp.toString(); // return a String created from the StringBuffer } public static void main ( String[] args ) { System.out.println( reverse( "Hello" ) ); } }
Does this program make any assumptions about the size of the
original String
?